package so.wy.servicecenter.businessbed.service.user;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import so.wy.servicecenter.auth.birdge.out.TokenOutManager;
import so.wy.servicecenter.base.exception.ManagerException;
import so.wy.servicecenter.base.exception.ServiceException;
import so.wy.servicecenter.base.frame.service.AbstractService;
import so.wy.servicecenter.businessbed.dao.enums.StatusOrderEnum;
import so.wy.servicecenter.businessbed.dao.enums.StatusUserDepositEnum;
import so.wy.servicecenter.businessbed.dao.rdb.order.order.OrderDAO;
import so.wy.servicecenter.businessbed.dao.rdb.order.order.OrderDO;
import so.wy.servicecenter.businessbed.dao.rdb.rent_user.RentUserDAO;
import so.wy.servicecenter.businessbed.dao.rdb.rent_user.RentUserDO;
import so.wy.servicecenter.businessbed.extend.UserAppOutManager;
import so.wy.servicecenter.businessbed.manager.normal.wx.WxDecodeDTO;
import so.wy.servicecenter.businessbed.manager.normal.wx.WxSessionDTO;
import so.wy.servicecenter.businessbed.manager.normal.wx.WxToolNManager;
import so.wy.servicecenter.businessbed.service.order.dto.OrderDTO;
import so.wy.servicecenter.businessbed.service.rentuser.dto.RentUserDetailsDTO;
import so.wy.servicecenter.platformuser.birdge.out.PlatformUserOutManager;
import so.wy.servicecenter.platformuser.dao.enums.TypeThirdEnum;
import so.wy.servicecenter.platformuser.dao.rdb.platform_user_third.PlatformUserThirdDO;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Scope("prototype")
public class TUserAppService extends AbstractService {
    @Autowired
    private PlatformUserOutManager userOutManager;

    @Autowired
    protected TokenOutManager tokenOutManager;

    @Autowired
    private UserAppOutManager userAppOutManager;

    @Autowired
    private RentUserDAO rentUserDAO;

    @Autowired
    private WxToolNManager wxToolNManager;

    @Autowired
    private OrderDAO orderDAO;


    //微信登陆或注册
    public String userWxLoginOrRegister(String ip, String openId, String phone) throws ServiceException {
        PlatformUserThirdDO thridUser = userOutManager.getThridUser(TypeThirdEnum.WX_MP, "", openId);
        Long userId;
        try {
            if (thridUser == null) {
                userId = this.userOutManager.thridRegister(TypeThirdEnum.WX_MP, "", openId, "", "", "123456");

                //更新用户手机号
                userAppOutManager.updateUserPhone(userId, phone);

                //添加租户信息
                RentUserDO rentUserDO = new RentUserDO();
                rentUserDO.setUserId(userId);
                rentUserDO.setRentUserPhone(phone);
                rentUserDO.setDepositStatus(StatusUserDepositEnum.NOTPAYD.getCode());
                rentUserDO.setDepositAmount(new BigDecimal(0));
                rentUserDAO.insert(rentUserDO);

            } else {
                userId = thridUser.getUserId();
            }

            userOutManager.userLogin(ip, userId, null);

            return tokenOutManager.loginByToken(userId);
        } catch (ManagerException e) {
            throw exception(e.getMessage());
        }
    }

    /**
     * 更新用户
     */
    public void updateUser(long userId, String name, String icon) throws ServiceException {
        userAppOutManager.updateUserNameIcon(userId, name, icon);

        RentUserDO upDO = new RentUserDO();
        upDO.setRentUserName(name);
        upDO.setRentUserIcon(icon);
        rentUserDAO.update(upDO, new LambdaQueryWrapper<RentUserDO>().eq(RentUserDO::getUserId, userId));
    }

    //获取租赁用户信息
    public RentUserDetailsDTO getRentUserInfo(Long userId){
        RentUserDO rentUserDO = rentUserDAO.selectOne(new LambdaQueryWrapper<RentUserDO>().eq(RentUserDO::getUserId, userId));

        RentUserDetailsDTO rentUserDetailsDTO =  new RentUserDetailsDTO(rentUserDO);

        //获取租户当前正在进行的订单
        List<OrderDO> orderDOS = orderDAO.selectList(new LambdaQueryWrapper<OrderDO>().eq(OrderDO::getRentUserId, rentUserDO.getRentUserId())
                .eq(OrderDO::getOrderStatus, StatusOrderEnum.PROCESSING.getCode()));
        rentUserDetailsDTO.setRentingOrder(orderDOS==null?new ArrayList<>():orderDOS.stream().map(OrderDTO::new).collect(Collectors.toList()));

        return rentUserDetailsDTO;
    }

    //获取微信session
    public WxSessionDTO getWxProCode2Session(String jsCode) throws ServiceException {
        try {
            return wxToolNManager.getWxProCode2Session(jsCode);
        } catch (ManagerException e) {
            throw exception(e.getMessage());
        }
    }

    //解密用户信息
    public WxDecodeDTO decrypt(String encryptedData, String sessionKey, String iv) throws ServiceException {
        try {
            return wxToolNManager.decrypt(encryptedData, sessionKey, iv);
        } catch (ManagerException e) {
            try {
                return wxToolNManager.decrypt(encryptedData, sessionKey, iv);
            } catch (ManagerException ex) {
                throw exception("微信获取数据异常，请点击退出后，重新进行登录");
            }
        }
    }
}
